import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      num: 0
    },
    children: [
      {
        path: '/home/SearchPopup',
        name: 'SearchPopup',
        component: () => import(/* webpackChunkName: "SearchPopup" */'../views/SearchPopup.vue')

      }
    ]
  },
  // 404
  {
    path: '/lo',
    name: 'lo',
    component: () => import(/* webpackChunkName: "lo" */'../views/lo.vue')
  },
  // 商品详情
  {
    path: '/Details',
    name: 'Details',
    component: () => import(/* webpackChunkName: "Details" */'../views/Details.vue')
  },
  // 品牌制造商
  {
    path: '/Brand',
    name: 'Brand',
    component: () => import(/* webpackChunkName: "Details" */'../views/Brand.vue')
  },
  // 最难分类
  {
    path: '/Kind',
    name: 'Kind',
    component: () => import(/* webpackChunkName: "Kind" */'../views/Kind.vue')
  },
  {
    path: '/Template',
    name: 'Template',
    meta: {
      num: 1
    },
    component: () => import(/* webpackChunkName: "Template" */'../views/Template.vue')
  },
  {
    path: '/Type',
    name: 'Type',
    meta: {
      num: 2
    },
    component: () => import(/* webpackChunkName: "Type" */'../views/Type.vue')
  },
  // 购物车
  {
    path: '/Car',
    name: 'Car',
    meta: {
      num: 3
    },
    component: () => import(/* webpackChunkName: "Car" */'../views/Car.vue')
  },
  // 我的
  {
    path: '/Me',
    name: 'Me',
    meta: {
      num: 4
    },
    component: () => import(/* webpackChunkName: "Car" */'../views/Me.vue')
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// router.beforeEach((to, from, next) => {
//   if (to.path == '/Me' || to.path == '/register') {
//     next();
//   } else {
//     alert('您还没有登录，请先登录');
//     next('/Me');
//   }
// })


router.beforeEach((to, from, next) => {
  // console.log("to", to);//去哪
  // console.log("from", from);//从哪来
  //判断登陆状态,如果登录了,就可以跳转购物车页,否则去登陆
  let token = localStorage.getItem("username");
  if (to.path == "/Car") {
    if (token) {
      next()
    } else {
      setTimeout(() => {
        next('/Me')
      }, 1000)
    }
    return;
  }
  next()
})




export default router
